package com.example.gcmtest1;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class GoogleWebView extends Activity implements View.OnClickListener {

	public final static String CLIENT_ID = "518191396700-pugvi7p2l6objo3tr3jfhcnfvgasfnq9.apps.googleusercontent.com";
	public final static String CLIENT_SECRET = "_28j_OF1SW24nTBR80pW2VHm";
	
	protected WebView webview1;
	private Button cmdAuthen, cmdRenewToken, cmdTest1, cmdTest2;
	private GoogleWebViewClient wClient;
	protected TextView lblResult;
	protected LinearLayout layoutMain;
	
	private String logName = "GoogleWebView";
	
	private String accessToken = "";
	private String refreshToken = "";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_google_web_view);
        
        
        
        this.webview1 = (WebView) this.findViewById(R.id.webview1);
        this.cmdAuthen = (Button) this.findViewById(R.id.cmdAuthen);
        this.cmdRenewToken = (Button) this.findViewById(R.id.cmdRenewToken);
        this.cmdTest1 = (Button) this.findViewById(R.id.cmdTest1);
        this.cmdTest2 = (Button) this.findViewById(R.id.cmdTest2);
        this.lblResult = (TextView) this.findViewById(R.id.lblResult);
        this.layoutMain = (LinearLayout) this.findViewById(R.id.layoutMain);
        
        this.webview1.getSettings().setJavaScriptEnabled(true);
        this.cmdAuthen.setOnClickListener(this);
        this.cmdRenewToken.setOnClickListener(this);
        this.cmdTest1.setOnClickListener(this);
        this.cmdTest2.setOnClickListener(this);
        this.cmdRenewToken.setEnabled(false);
        
        this.wClient = new GoogleWebViewClient(this);
        this.webview1.setWebViewClient(this.wClient);        
     
        LinearLayout l  = (LinearLayout) this.findViewById(R.id.linearLayout1);
        if (l != null) {
        	//l.setVisibility(View.INVISIBLE);
        }
        
        //this.webview1.setVisibility(View.INVISIBLE);
        
    }
    
    protected void setAccessToken(String accessToken) {
    	this.accessToken = accessToken;
    	if (accessToken.equals("") == false) {
    		this.cmdRenewToken.setEnabled(true);
    	}
    	
    }
    
    protected void setRefreshToken(String refreshToken) {
    	this.refreshToken = refreshToken;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_google_web_view, menu);
        return true;
    }

	@Override
	public void onClick(View arg0) {
		if (arg0 == this.cmdAuthen) {
			String scope = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com";
			String state = "offline";
			String responseType = "code";
			String redirectUri = "http://localhost";
			
			String url = "https://accounts.google.com/o/oauth2/auth?";
			url = url + "client_id=" + URLEncoder.encode(GoogleWebView.CLIENT_ID);
			url = url + "&scope=" + URLEncoder.encode(scope);
			url = url + "&state=" + URLEncoder.encode(state);
			url = url + "&response_type=" + URLEncoder.encode(responseType);
			url = url + "&redirect_uri=" + URLEncoder.encode(redirectUri);
			
			Log.d(logName, "url=" + url);
			
			this.webview1.loadUrl(url);
			
		} else if (arg0 == this.cmdRenewToken) {
			new RefreshTokenTask().execute("");
			
		} else if (arg0 == this.cmdTest1) {
			this.layoutMain.removeView(this.webview1);
			
			
		} else if (arg0 == this.cmdTest2) {
			this.layoutMain.addView(this.webview1, 1);
		}
		
		
	}
	
	private class RefreshTokenTask extends AsyncTask<String, Integer, Long> {

		private String logName = "RefreshTokenTask";
		
		public String getRefreshedToken() {
			String refreshedToken = "";
			
			Log.d(this.logName, "refreshing token..");
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token");
			
			try {
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken));
				nameValuePairs.add(new BasicNameValuePair("client_id", GoogleWebView.CLIENT_ID));
				nameValuePairs.add(new BasicNameValuePair("client_secret", GoogleWebView.CLIENT_SECRET));
				nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
				//nameValuePairs.add(new BasicNameValuePair("redirect_uri", "http://localhost"));
				//nameValuePairs.add(new BasicNameValuePair("response_type", "code"));
								
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		        // Execute HTTP Post Request
		        HttpResponse response = httpClient.execute(httpPost);
		        
		        String ret = EntityUtils.toString(response.getEntity());
		        Log.d(logName, ret);
		        		        
		        JSONObject jsObj = new JSONObject(ret);
		        String accessToken = jsObj.getString("access_token");
		        //String refreshToken = jsObj.getString("refresh_token");
		        Log.d(logName, "refreshed, accessToken=" + accessToken);
		        //Log.d(logName, "refreshToken=" + refreshToken);
		        
		        //this.parent.setAccessToken(accessToken);
		        //this.parent.setRefreshToken(refreshToken);
		        refreshedToken = accessToken;
		        
			} catch (Exception e) {
				Log.e(logName, "RefreshTokenTask \n" + e.toString());
			}			
			
			return(refreshedToken);
		}
		
		@Override
		protected Long doInBackground(String... params) {

			String refreshedToken = this.getRefreshedToken();
			setAccessToken(refreshedToken);
			
			SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
	        pref.edit().putString("accessToken", refreshedToken);
			
			return 1l;
		}
		
	}

    
}
